<!DOCTYPE html>
<html lang=zh-CN>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:description" content="samuel-24276的博客">
    <meta property="og:type" content="website">
    <meta name="description" content="samuel-24276的博客">
    <meta name="keyword"  content="aircloud">
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
        左值引用与右值引用 - samuel-24276的博客 | samuel-24276&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/myblog/css/aircloud.css">

    
<link rel="stylesheet" href="/myblog/css/gitment.css">

    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_28hi1hpxx24.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 7.1.1"></head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> Like what you do, do what you like </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar ">
            <img src="/myblog/img/avatar.jpg" />
        </div>
        <div class="name">
            <i>samuel-24276</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li >
                <a href="/myblog/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li >
                <a href="/myblog/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li >
                <a href="/myblog/archives">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li >
                <a href="/myblog/collect/">
                    <i class="iconfont icon-shoucang1"></i>
                    <span>收藏</span>
                </a>
            </li>
            <li >
                <a href="/myblog/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1-%E5%8C%BA%E5%88%AB"><span class="toc-text">1.区别</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89"><span class="toc-text">定义</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BE%8B%E5%AD%90"><span class="toc-text">例子</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%9C%89%E6%97%A0%E4%BE%8B%E5%A4%96"><span class="toc-text">有无例外</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%A7%BB%E5%8A%A8%E8%AF%AD%E4%B9%89"><span class="toc-text">移动语义</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%AE%8C%E7%BE%8E%E8%BD%AC%E5%8F%91"><span class="toc-text">完美转发</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%95%E7%94%A8%E6%8A%98%E5%8F%A0%E8%A7%84%E5%88%99"><span class="toc-text">引用折叠规则</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#forward-v"><span class="toc-text">forward(v)</span></a></li></ol></li></ol>
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-bg" id="search-bg"></div>
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input"/>
            <span id="begin-search">搜索</span>
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>

        <div class="index-about-mobile">
            <i> Like what you do, do what you like </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        左值引用与右值引用
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2020-06-17 16:03:18</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/myblog/tags/#C++" title="C++">C++</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>
</span>
    </div>
    <div class="post-content no-indent">
        <h1 id="1-区别"><a href="#1-区别" class="headerlink" title="1.区别"></a>1.区别</h1><p>左值引用避免拷贝，可以用于函数传参、函数返回值；<br>右值引用实现了移动语义和完美转发</p>
<h1 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h1><p>左值：可以在等号（赋值）左边，可以取地址，具名的<br>右值：只能在等号右边，不能取地址，不具名</p>
<h1 id="例子"><a href="#例子" class="headerlink" title="例子"></a>例子</h1><p>左值例子：变量名，返回左值引用的函数调用、前置的自增和自减、赋值或复合赋值运算、解引用</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> val = <span class="number">0</span>;</span><br><span class="line">++val;</span><br><span class="line">(val = <span class="number">9</span>) = <span class="number">100</span>;</span><br><span class="line">(val) += <span class="number">2</span>;</span><br></pre></td></tr></table></figure>

<p>右值例子：纯右值和将亡值<br>纯右值：字面值、返回非引用类型的函数调用、后置自增&#x2F;自减、算术&#x2F;逻辑&#x2F;比较表达式<br>将亡值（C++11新引入，和移动语义和完美转发有关）：用来触发移动构造&#x2F;移动赋值构造函数，并进行资源转移，之后调用析构函数</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 若T有移动构造/移动赋值构造函数，则CreateT()是右值（将亡值）</span></span><br><span class="line"><span class="comment">// 正常带优化的只会调用一次构造和析构函数，禁掉返回值优化：-fo-elide-constructors后按以下顺序构造：</span></span><br><span class="line"><span class="comment">// 1.看类有没有移动构造</span></span><br><span class="line"><span class="comment">// 2.看类有没有拷贝构造</span></span><br><span class="line"><span class="comment">// 3.报错</span></span><br><span class="line">T t = <span class="built_in">CreateT</span>();</span><br></pre></td></tr></table></figure>

<h1 id="有无例外"><a href="#有无例外" class="headerlink" title="有无例外"></a>有无例外</h1><p>const左值引用可以引用右值<br>右值引用通过std::move(val)可以指向左值</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> &amp;&amp; j = <span class="number">100</span>;<span class="comment">// 声明右值引用</span></span><br><span class="line"><span class="type">int</span> &amp; k = i;<span class="comment">// 声明左值引用</span></span><br><span class="line"><span class="comment">// 声明出来的左值引用和右值引用都是左值</span></span><br></pre></td></tr></table></figure>

<h1 id="移动语义"><a href="#移动语义" class="headerlink" title="移动语义"></a>移动语义</h1><p>解决问题：对象赋值时，避免资源的重新分配（直接移动指针）<br>实现方式：移动构造&#x2F;移动赋值构造函数</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Cls a,b;</span><br><span class="line">a = b;<span class="comment">// 拷贝构造</span></span><br><span class="line">Cls *c = <span class="keyword">new</span> <span class="built_in">Cls</span>();</span><br><span class="line">Cls *d = <span class="literal">nullptr</span>;</span><br><span class="line">d = c;<span class="comment">// 深拷贝，涉及资源拷贝</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">因为拷贝函数是const引用，所以无法将c的内部数据指针置空，将d的内部数据指针</span></span><br><span class="line"><span class="comment">指向该资源；只能重新申请空间，将c的内部数据复制到指向该空间的指针。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line">Cls e;</span><br><span class="line"><span class="function">Cls <span class="title">f</span><span class="params">(std::move(e))</span></span>;<span class="comment">// 右值才会触发移动构造函数，通过std::move(e)将e的资源迁移到f</span></span><br><span class="line"></span><br><span class="line">list&lt;Cls&gt; cls_list;</span><br><span class="line">cls_list.<span class="built_in">push_back</span>(<span class="built_in">Cls</span>());<span class="comment">// Cls()是不具名的临时对象（将亡值），从而触发移动构造函数</span></span><br></pre></td></tr></table></figure>

<h1 id="完美转发"><a href="#完美转发" class="headerlink" title="完美转发"></a>完美转发</h1><p>定义：函数模板可以完美地将自己的参数转发给内部调用的其他函数（完美指不仅能准确地接收&#x2F;转发参数的值，还能保证被转发的参数的左右值属性不变）<br>用在模板函数中</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="type">void</span> <span class="title">func</span><span class="params">(<span class="type">int</span> &amp;n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    cout&lt;&lt;<span class="string">&quot;lvalue=&quot;</span> &lt;&lt; n &lt;&lt; endl;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">func</span><span class="params">(<span class="type">int</span> &amp;&amp;n)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    cout&lt;&lt;<span class="string">&quot;rvalue=&quot;</span> &lt;&lt; n &lt;&lt; endl;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">revoke</span><span class="params">(T t)</span><span class="comment">//A</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">func</span>(t);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">revoke</span><span class="params">(T&amp; t)</span><span class="comment">//B</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">func</span>(t);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">revoke</span><span class="params">(<span class="type">const</span> T&amp; t)</span><span class="comment">//C</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">func</span>(t);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">revoke</span><span class="params">(T&amp;&amp; t)</span><span class="comment">// D</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">func</span>(t);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt;<span class="keyword">typename</span> T&gt;</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">revoke</span><span class="params">(T&amp;&amp; t)</span><span class="comment">// E</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="built_in">func</span>(std::forward&lt;T&gt;(t));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>A版本的revoke(n)无法调用右值版本的func()，因为参数t是具名的左值；<br>B版本的revoke(n)可以调用左值版本的func()；C版本的revoke(n)可以转发右值，<br>但不能修改，不能达到很好的转发。<br>E版本的revoke(n)可以在n是左值时调用左值版本的func(n)，可以在n是右值时<br>调用右值版本的func(n)。</p>
<p>实现方法：借助万能引用（T &amp;&amp;t&#x2F;auto &amp;&amp;t）通过引用的方式接收左右属性的值</p>
<h2 id="引用折叠规则"><a href="#引用折叠规则" class="headerlink" title="引用折叠规则"></a>引用折叠规则</h2><blockquote>
<p>保证准确接收参数的值</p>
</blockquote>
<ol>
<li>参数为左值引用，     T &amp;&amp; -&gt; T &amp;&amp; &amp; -&gt; T &amp;</li>
<li>参数为左值，         T &amp;&amp; -&gt;T &amp;</li>
<li>参数为右值或右值引用，T &amp;&amp; -&gt; T &amp;&amp; &amp;&amp; -&gt; T&amp;&amp;</li>
</ol>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> i = <span class="number">10</span>;</span><br><span class="line"><span class="type">int</span> &amp;m = i;</span><br><span class="line"><span class="type">int</span> &amp;&amp; n= <span class="number">100</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 逐步放开B、C、D、E的revoke，以下内容有不同输出结果</span></span><br><span class="line"><span class="built_in">revoke</span>(<span class="number">10</span>);</span><br><span class="line"><span class="built_in">revoke</span>(i);</span><br><span class="line"><span class="built_in">revoke</span>(m);</span><br><span class="line"><span class="built_in">revoke</span>(n);</span><br></pre></td></tr></table></figure>

<h2 id="forward-v"><a href="#forward-v" class="headerlink" title="forward(v)"></a>forward<V>(v)</h2><blockquote>
<p>保证转发参数的值和左右值属性不变</p>
</blockquote>
<p>V为左值引用，v转换为V类型的左值<br>V为右值引用，v转化为V类型的右值</p>
<hr>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src="" data-src="/myblog/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br />
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>
        <div id="lv-container"></div>
        <div class="giscus"></div>
    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        

        

        
        <li>
            <a target="_blank"  href="https://github.com/samuel-24276">
                            <span class="fa-stack fa-lg">
                                <i class="iconfont icon-github"></i>
                            </span>
            </a>
        </li>
        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://github.com/samuel-24276">samuel-24276&#39;s Page</a></span>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">北京-未备案</a></span>
        <span>/</span>
        
        <span><a href="#">返回顶部</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>  Theme <a target="_blank" rel="noopener" href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/myblog/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script src="/myblog/js/index.js"></script>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






    <script type="text/javascript">
       (function() {
           if (typeof LivereTower === 'function') { return; }

           var j, d = document.getElementById('lv-container');

           d.setAttribute('data-id','city');
           d.setAttribute('data-uid' , 'MTAyMC80OTA5OC8yNTU5Mw==');

           j = document.createElement('script');
           j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
           j.async = true;

           d.appendChild(j);
       })();
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

</html>
